package com.jeespring.admin.service;

import com.jeespring.admin.dao.ResourceDao;
import com.jeespring.common.constant.SystemConstant;
import com.jeespring.common.pojo.TreeNode;
import com.jeespring.admin.entity.Resource;
import com.jeespring.admin.entity.ResourceExample;
import com.jeespring.admin.entity.ResourceExample.Criteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @title:
 * @description:
 * @author: 张朝阳
 * @date: 2019/5/1 00:17
 */

@Service
public class ResourceService {

    @Autowired
    private ResourceDao resourceDao;

    public List<Resource> getResourceList(){

        ResourceExample example = new ResourceExample();
        Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(SystemConstant.StatusType.VALID.getCode());
        List<Resource> resourcesList = resourceDao.selectByExample(example);

        return resourcesList;
    }

    public List<TreeNode> getMenuList(){
        Map<Long, List<TreeNode>> menuTree = new HashMap<Long, List<TreeNode>>();
        //获取treeNodeList
        List<TreeNode> treeNodeList = resourceDao.getMenuList();
        for (TreeNode treeNode : treeNodeList) {
            Long parentId = treeNode.getParentId();
            List<TreeNode> subTree = menuTree.get(parentId);
            if (subTree == null) {
                subTree = new ArrayList<TreeNode>();
                menuTree.put(parentId, subTree);
            }
            subTree.add(treeNode);
        }
        List<TreeNode> menuList = menuTree.get(SystemConstant.ROOT_NODE);
        if(menuList == null){
            return null;
        }
        for (TreeNode node : menuList) {
            if (!SystemConstant.NodeType.LEAF.getCode().equals(node.getNodeFlag()) ){
                getMenu(node , menuTree , node.getId());
            }
        }
        return menuList;
    }

    private void getMenu(TreeNode treeNode ,Map<Long ,List<TreeNode>> menuTree,Long parentId) {
        List<TreeNode> subTree = menuTree.get(parentId);
        if(subTree == null){
            return;
        }
        treeNode.setTreeNodeList(subTree);
        for (TreeNode node : subTree) {
            if (!SystemConstant.NodeType.LEAF.getCode().equals(node.getNodeFlag())){
                getMenu(node , menuTree , node.getId());
            }
        }

    }
}
